// pages/miners/minerList.js
import api from "../../utils/apis.js";
import message from "../../utils/message.js";
import util from "../../utils/util.js"

Page({
  data: {
    deviceList: [],
    deviceDetail: null,

    pageSize: 20,
    pageNum: 0,
    bottomTitle: '点击加载更多'
  },

  onLoad: function(options) {
    wx.startPullDownRefresh()
  },

  onPullDownRefresh: function () {
    let self = this;

    self.setData({
      pageNum: 0
    })

    self.getDeviceData();
    self.getDeviceList(self.data.pageNum);
  },

  onReachBottom: function () {
    let self = this

    if (self.data.bottomTitle === '无更多数据') {
      return
    }

    self.loadMore()
  },

  loadMore() {
    let self = this

    if (self.data.bottomTitle === '无更多数据') {
      return
    }

    let temp = self.data.pageNum;
    temp += 1;
    self.setData({
      pageNum: temp
    });

    self.getDeviceList(self.data.pageNum)
  },

  getDeviceData() {
    let self = this;
    let token = wx.getStorageSync("authorization");

    wx.showLoading({
      title: "加载中"
    });
    wx.request({
      url: api.deviceInfoHeadApi,
      method: "GET",
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        wx.stopPullDownRefresh()

        if (res.statusCode == "200") {
          self.setData({
            deviceDetail: res.data
          })
        } else {
          util.errHandler(res)
        }
      }
    });
  },

  getDeviceList(pageNum) {
    let self = this;
    let token = wx.getStorageSync("authorization");

    wx.showLoading({
      title: "加载中"
    });
    wx.request({
      url: api.deviceListApi + "?" + "page=" + pageNum + "&size=" + self.data.pageSize,
      method: "get",
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        if (res.statusCode == "200") {

          if (res.data.length == 0) {
            self.setData({
              bottomTitle: '无更多数据'
            });
            return
          }

          if (self.data.pageNum == 0) {
            self.setData({
              deviceList: []
            })
          }

          let temp = []
          self.data.deviceList.forEach(element => {
            element.devId = util.hideWord(element.devId)
            temp.push(element)
          })

          res.data.forEach(element => {
            element.devId = util.hideWord(element.devId)
            temp.push(element)
          })

          self.setData({
            deviceList: temp
          })
        } else {
          util.errHandler(res)
        }
      }
    });
  }
})